﻿using DtoFw;
using DtoFw.Enum;
using Hangfire;
using Repository;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Util;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using DtoFw.DataStandardApi;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Ocsp;
using Domain.Base;
using Domain.Entity;
using System.Net.Http;
using Serilog;
using Google.Protobuf.WellKnownTypes;

namespace Service
{
    public class TaskService
    {
        //隔多久执行
        //RecurringJob.AddOrUpdate("1", () => A(), "* 52 15 12 4 *");   //每年的4月12号15点52分任意秒执行 没加时区 小时+8
        //RecurringJob.AddOrUpdate("2", () => A(), Cron.Minutely);      //每分钟执行一次。
        //RecurringJob.AddOrUpdate("3", () => A(), Cron.Daily(18, 36), TimeZoneInfo.Local);  //每天18点36分 当前时区
        //RecurringJob.AddOrUpdate<ITaskInterface>(x => x.Test(), Cron.Daily(18, 25),TimeZoneInfo.Local);
        private readonly IRecurringJobManager _recurringJobManager;
        private readonly MainDicService _dicService;
        private readonly EarlyWarningService _earlyWarningService;
        private readonly MainHomeService _mainConfigService;
        private readonly DbBakService _dbBakService;
        private readonly MainConfigRepository _configRepository;
        private readonly CasePhysicalEvidenceRepository _casePhysicalEvidenceRepository;

        public TaskService(CasePhysicalEvidenceRepository casePhysicalEvidenceRepository, MainConfigRepository configRepository)
        {
            this._recurringJobManager = EngineContext.Resolve<IRecurringJobManager>();
            this._dicService = EngineContext.Resolve<MainDicService>();
            this._earlyWarningService = EngineContext.Resolve<EarlyWarningService>();
            this._mainConfigService = EngineContext.Resolve<MainHomeService>();
            this._dbBakService = EngineContext.Resolve<DbBakService>();
            this._configRepository = configRepository;
            this._casePhysicalEvidenceRepository = casePhysicalEvidenceRepository;
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <returns></returns>
        [Obsolete]
        public BaseResult PulseOnHangfireServer()
        {
            this._recurringJobManager.AddOrUpdate("EarlyWarnEvidenceUnbound",
                () => EarlyWarnEvidenceUnbound(), Cron.MinuteInterval(5));

            return BaseResult.Succeed();
        }

        #region 预警接口

        /// <summary>
        /// 物品未绑定
        /// </summary>
        /// <returns></returns>
        public bool EarlyWarnEvidenceUnbound()
        {
            return _earlyWarningService.EarlyWarnEvidenceUnbound();
        }

        /// <summary>
        /// 未及时入库
        /// </summary>
        /// <returns>是否成功</returns>
        public bool EarlyWarnOvertimeStock()
        {
            return _earlyWarningService.EarlyWarnOvertimeStock();
        }

        /// <summary>
        /// 未及时回库
        /// </summary>
        /// <returns>是否成功</returns>
        public bool EarlyWarnOvertimeRevert()
        {
            return _earlyWarningService.EarlyWarnOvertimeRevert();
        }

        /// <summary>
        /// 保存超期
        /// </summary>
        /// <returns>是否成功</returns>
        public bool EarlyWarnOvertimeSave()
        {
            return _earlyWarningService.EarlyWarnOvertimeSave();
        }

        /// <summary>
        /// 库容爆仓
        /// </summary>
        /// <returns>是否成功</returns>
        public bool EarlyWarnStockQuantity()
        {
            return _earlyWarningService.EarlyWarnStockQuantity();
        }

        public bool DbBakTask()
        {
            return _dbBakService.DbBakTask();
        }

        public bool SendTestMsg()
        {
            var sw = new System.IO.StreamWriter("d:\\a.txt", true);
            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            sw.Close();
            try
            {
                _earlyWarningService.SendTestMsg();
            }
            catch (Exception)
            {

            }
            return true;
        }

        public bool PingWebSocket()
        {
            WebSocketModel.SendJson("ping", new List<string>());
            return true;
        }

        public int GetInterval(string warnType)
        {
            return 0;
        }

        #endregion

        #region 执法办案管理中心信息系统

        public void RunDataStandardTask(string cfrom)
        {
            try
            {
                Log.Information($"执法办案管理中心信息系统，开始执行。");
                //读取配置文件
                var config = GetDataStandardConfig();
                //解析配置
                var ty = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(config.Content, new { preTime = DateTime.Now.AddDays(-7) });
                if (cfrom == "hand")
                {
                    //手动执行
                    ty = new { preTime = DateTime.Parse("2024-8-1") };
                }
                //当前时间
                var curTime = DateTime.Now;

                var token = GetToken();

                //2.2 涉案物品基本信息
                List<string> ids = TabSacwWpGbJbxx(token, ty.preTime);
                //2.3 涉案物品流转明细信息
                TabSacwGoodsTransfer(token, ty.preTime, ids);
                //2.4 涉案物品入库信息
                //TabSawpRkxx(token, ty.preTime, ids);
                //2.6 涉案物品出库信息
                //TabSawpCkxx(token, ty.preTime, ids);
                //2.1 涉案物品附件信息
                TabSacwglWpfjb(token, ty.preTime, ids);

                //更新最新执行时间
                config.Content = Newtonsoft.Json.JsonConvert.SerializeObject(new { preTime = curTime }, new Newtonsoft.Json.Converters.IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
                config.ModifyerTime = DateTime.Now;
                _configRepository.Save(config);

                Log.Information($"执法办案管理中心信息系统，执行结束。");

            }
            catch (Exception ex)
            {
                Log.Information($"执法办案管理中心信息系统，数据推送任务执行失败\n{ex.ToString()}");
            }
        }

        /// <summary>
        /// 2.1 涉案物品附件信息（只给照片）
        /// </summary>
        void TabSacwglWpfjb(string token, DateTime preTime, List<string> ids)
        {
            string sql = $@"SELECT CONCAT('HYD',s1.id) as `sId`,
                                   CONCAT(s2.`Id`,'') as lybid,
                                   s1.Name as fjmc,
                                   s1.Url as fjlj,
                                   s2.`No` as wpbh,
                                   IF(s1.isdeleted,'1','0') as sfsc,
                                   DATE_FORMAT(s1.`CreateTime`,'%Y-%m-%d %H:%i:%s') as tjsj,
                                   DATE_FORMAT(s1.`ModifyerTime`,'%Y-%m-%d %H:%i:%s') as gxsj,
                                   'F' as xtly,
                                   '恒亦达信息科技(苏州)有限公司' as sjsbcj
                              FROM system_annex_img s1 
                              join case_physical_evidence s2 on s1.`RelevanceNo`=s2.`No` 
                             where (s1.`ModifyerTime`>='{preTime.ToString("yyyy-MM-dd HH:mm:ss")}' OR s1.id in({string.Join(",", ids)}))  
                               and s2.`PushSucc` is not null ";
            var list = this._configRepository.GetDb().SqlQueryable<dynamic>(sql).ToList();
            if (list != null && list.Count > 0)
            {
                var ret = Ajax<string>("/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwglWpfjb", list, token);
                if (ret.Success)
                {
                    Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwglWpfjb，\n2.1 涉案物品附件信息成功：【{Newtonsoft.Json.JsonConvert.SerializeObject(list)}】");
                }
                else
                {
                    Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwglWpfjb，\n2.1 涉案物品附件信息失败：【{Newtonsoft.Json.JsonConvert.SerializeObject(new { ret, list })}】");
                }
            }
            else
            {
                Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwglWpfjb，\n2.1 涉案物品附件信息：数据库查询无数据");
            }
        }
        /// <summary>
        /// 2.2 涉案物品基本信息
        /// </summary>
        List<string> TabSacwWpGbJbxx(string token, DateTime preTime)
        {
            var retLs = new List<string>() { "0" };
            string sql = $@"SELECT CONCAT('HYD',s1.id) as `sId`,
                                   s1.`Id` as lybid,
                                   s2.`CaseNo` as ajbh,
                                   s2.`CaseName` as ajmc,
                                   s2.`HostUserId` as cbrbm,
                                   s2.`HostUserName` as cbrmc,
                                   s2.`HostUserName` as ycyrxm,
                                   s3.`ComNo` as cbdwbm,
                                   s3.`Name` as cbdwmc,
                                   s1.`No` as wpbh,
                                   s1.`Name` as wpmc,
                                   s1.`Quantity` as wpsl,
                                   s1.`ExtractionPersonName` as wpysmc,
                                   s1.`ClassName` as wplxmc,
                                   s1.`CategoryName` as wpdlmc,
                                   s1.`subCategoryName` as wpxlmc,
                                   s1.`ExtractMethod` as wplymc,
                                   s1.`Describe` as wptz,
                                   s1.`Source` as wpgg,
                                   s1.`Remark` as bz,
                                   s1.`Shape` as wpxzmc,
                                   s1.`Creator` as djrmc,
                                   s1.`OrganName` as djdwmc,
                                    (case when s1.`Status`=0 then '10' 
                                         when s1.`Status`=1 then '40' 
                                         when s1.`Status`=2 then '60' end)  as wpztbm,
                                   DATE_FORMAT(s1.`CreateTime`,'%Y-%m-%d %H:%i:%s') as djsj,
                                   (case when s1.`Status`=0 then '2' 
                                         when s1.`Status`=1 then '1' 
                                         when s1.`Status`=2 then '2' end)  as bgztbm,
                                   DATE_FORMAT(s1.`CreateTime`,'%Y-%m-%d %H:%i:%s') as tjsj,
                                   IF(s1.isdeleted,'1','0') as sfsc,
                                   DATE_FORMAT(s1.`ModifyerTime`,'%Y-%m-%d %H:%i:%s') as gxsj,
                                   'F' as xtly,
                                   '恒亦达信息科技(苏州)有限公司' as sjsbcj,
                                   DATE_FORMAT(s1.`PushSucc`,'%Y-%m-%d %H:%i:%s') as pushSucc
                              FROM case_physical_evidence s1
                              join cases s2 on s1.`CaseId`=s2.`Id` 
                              left join system_organ s3 on IF(s2.`HostUserOrgan`>0,s2.`HostUserOrgan`,s2.`OrganId`)=s3.`Id`
                             where s1.`ModifyerTime`>='{preTime.ToString("yyyy-MM-dd HH:mm:ss")}' 
                               AND IFNULL(s2.`CaseNo`,'')<>'' 
                               AND IFNULL(s2.`CaseName`,'')<>'' 
                               AND IFNULL(s1.`No`,'')<>'' 
                               AND IFNULL(s1.`Name`,'')<>''
                               AND IFNULL(s2.`HostUserName`,'')<>'' ";
            var list = this._configRepository.GetDb().SqlQueryable<TabSacwWpGbJbxxEntity>(sql).ToList();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    //物品照片
                    var imgs = _mainConfigService.GetImgs(item.wpbh, 1);
                    if (imgs != null && imgs.Data != null && imgs.Data.Count > 0)
                    {
                        item.wptpsl = imgs.Data.Count;
                        item.wptp = string.Join(",", imgs.Data.Select(v => v.Url));
                    }
                    item.cbrmc = item.cbrmc ?? "";
                    item.cbdwmc = item.cbdwmc ?? "";
                    item.cbdwbm = item.cbdwbm ?? "";
                    item.wpztmc = item.wpztbm == "10" ? "已登记" : (item.wpztbm == "40" ? "已入库" : "已出库");
                    //item.wpztbm = item.wpztbm == 0 ? 10 : (item.wpztbm == 1 ? 40 : 60);
                    item.bgztmc = item.bgztbm == "1" ? "在柜" : "不在柜";
                    var json = item;

                    var ret = Ajax<string>("/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwWpGbJbxx", new object[] { json }, token);
                    if (ret.Success)
                    {
                        if (string.IsNullOrEmpty(item.pushSucc))
                        {
                            //本次首次更新
                            retLs.Add(item.lybid);
                        }
                        Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwWpGbJbxx，\n2.2 涉案物品基本信息成功：【{Newtonsoft.Json.JsonConvert.SerializeObject(json)}】");
                    }
                    else
                    {
                        Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwWpGbJbxx，\n2.2 涉案物品基本信息失败：【{Newtonsoft.Json.JsonConvert.SerializeObject(new { ret, json })}】");
                    }
                }
                if (retLs.Count > 0)
                {
                    _casePhysicalEvidenceRepository.SetPushDate(retLs.ToArray());
                }
            }
            else
            {
                Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwWpGbJbxx，\n2.2 涉案物品基本信息：数据库查询无数据");
            }
            return retLs;
        }
        /// <summary>
        /// 2.3 涉案物品流转明细信息
        /// </summary>
        void TabSacwGoodsTransfer(string token, DateTime preTime, List<string> ids)
        {
            string sql = $@"SELECT CONCAT('HYD',s0.id) as `sId`,
                                   CONCAT(s1.`Id`,'') as lybid,
                                   s1.`No` as wpbh,
                                   s1.`Name` as wpmc,
                                   CONCAT(s0.`Id`,'') as lzid,
                                   DATE_FORMAT(s0.`CreateTime`,'%Y-%m-%d %H:%i:%s') as lzsj,
                                   0 as lzsl,
                                   0 as lzqxz,
                                   'M' as lzqxlx,
                                   s4.`UserNo` as sqrbh,
                                   s0.`Creator` as sqrxm,
                                   s3.`ComNo` as sqrbmbh,
                                   s3.`Name` as sqrbmmc,
                                   (case when s0.`DeliveryDicType`=8 then '0' 
                                         when s0.`DeliveryDicType`=1 then '10' 
                                         when s0.`DeliveryDicType`=6 then '11' 
                                         when s0.`DeliveryDicType`=5 then '20' 
                                         when s0.`DeliveryDicType`=3 then '30' 
                                         when s0.`DeliveryDicType`=7 then '40' end)  as lzlx,
                                  '30' as ztid,
                                   DATE_FORMAT(s0.`CreateTime`,'%Y-%m-%d %H:%i:%s') as sqtjsj,
                                   DATE_FORMAT(s0.`CreateTime`,'%Y-%m-%d %H:%i:%s') as cjsj,
                                   DATE_FORMAT(s0.`ModifyerTime`,'%Y-%m-%d %H:%i:%s') as zhgxsj,
                                   IF(s1.isdeleted,'1','0') as sfsc,
                                   DATE_FORMAT(s0.`CreateTime`,'%Y-%m-%d %H:%i:%s') as tjsj,
                                   DATE_FORMAT(s0.`ModifyerTime`,'%Y-%m-%d %H:%i:%s') as gxsj,
                                   'F' as xtly,
                                   '恒亦达信息科技(苏州)有限公司' as sjsbcj
                              FROM case_physical_evidence_transfere s0
                              join case_physical_evidence s1 on s0.`EvidenceId`=s1.`Id`
                              join cases s2 on s1.`CaseId`=s2.`Id` 
                              left join system_user s4 on s0.`CreatorId`=s4.`Id` 
                              left join system_organ s3 on s4.`OrgId`=s3.`Id`
                             where s0.`DeliveryDicType` in(1,3,5,6,7,8) 
                               AND (s0.`ModifyerTime`>='{preTime.ToString("yyyy-MM-dd HH:mm:ss")}' 
                                    OR s1.id in({string.Join(",", ids)})) AND s1.`PushSucc` is not null ";
            var list = this._configRepository.GetDb().SqlQueryable<dynamic>(sql).ToList();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    var ret = Ajax<string>("/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwGoodsTransfer", new object[] { item }, token);
                    if (ret.Success)
                    {
                        Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwGoodsTransfer，\n2.3 涉案物品流转明细信息成功：【{Newtonsoft.Json.JsonConvert.SerializeObject(item)}】");
                    }
                    else
                    {
                        Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwGoodsTransfer，\n2.3 涉案物品流转明细信息失败：【{Newtonsoft.Json.JsonConvert.SerializeObject(new { ret, item })}】");
                    }
                }
            }
            else
            {
                Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSacwGoodsTransfer，\n2.3 涉案物品流转明细信息：数据库查询无数据");
            }
        }
        /// <summary>
        /// 2.4 涉案物品入库信息
        /// </summary>
        void TabSawpRkxx(string token, DateTime preTime, List<string> ids)
        {
            string sql = $@"SELECT s2.`InspectionNo` as `bazxbh`,
                                    CONCAT(s1.`Id`,'') as lybid,
                                   s1.`No` as bjwpbm,
                                   s1.`No` as wpbh,
                                   s0.`Receiver` as jsrxm,
                                   DATE_FORMAT(s0.`DeliveryTime`,'%Y%m%d%H%i%s') as rksj,
                                   '01'  as bgfs,
                                   s0.`Location` as cfwz,
                                   (case when s0.`DeliveryDicType` = 8 then '1' else '2' end) as sjczlxdm,
                                   left(s3.`ComNo`,6) as sjly,
                                   DATE_FORMAT(s1.`CreateTime`,'%Y-%m-%d %H:%i:%s') as lrsj,
                                   s3.`ComNo` as lrdwdm,
                                   s3.`Name` as lrdwmc,
                                   s0.`Creator` as lrrxm,
                                   s4.`CardNo` as lrrsfzh,
                                   DATE_FORMAT(s1.`ModifyerTime`,'%Y%m%d%H%i%s') as xgsj,
                                   s3.`ComNo` as xgdwdm,
                                   s3.`Name` as xgdwmc,
                                   s0.`Creator` as xgrxm,
                                   s4.`CardNo` as xgrsfzh,
                                   CONCAT(s0.`Id`,'') as xxzjbh,
                                   '恒亦达信息科技(苏州)有限公司' as sjsbcj
                              FROM case_physical_evidence_transfere s0
                              join case_physical_evidence s1 on s0.`EvidenceId`=s1.`Id`
                              join cases s2 on s1.`CaseId`=s2.`Id` 
                              left join system_user s4 on s0.`CreatorId`=s4.`Id` 
                              left join system_organ s3 on s4.`OrgId`=s3.`Id`
                             where s0.`EvidenceStatus`=1
                               and `HistoryStatus`=0
                               and (s0.`ModifyerTime`>='{preTime.ToString("yyyy-MM-dd HH:mm:ss")}' OR s1.id in({string.Join(",", ids)})) 
                               and s1.`PushSucc` is not null ";
            var list = this._configRepository.GetDb().SqlQueryable<dynamic>(sql).ToList();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    var ret = Ajax<string>("/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSawpRkxx", new object[] { item }, token);
                    if (ret.Success)
                    {
                        Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSawpRkxx，\n2.4 涉案物品入库信息成功：【{Newtonsoft.Json.JsonConvert.SerializeObject(item)}】");
                    }
                    else
                    {
                        Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSawpRkxx，\n2.4 涉案物品入库信息失败：【{Newtonsoft.Json.JsonConvert.SerializeObject(new { ret, item })}】");
                    }
                }
            }
            else
            {
                Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSawpRkxx，\n2.4 涉案物品入库信息：数据库查询无数据");
            }
        }
        /// <summary>
        /// 2.6 涉案物品出库信息
        /// </summary>
        void TabSawpCkxx(string token, DateTime preTime, List<string> ids)
        {
            string sql = $@"SELECT s2.`InspectionNo` as `bazxbh`,
                                   CONCAT(s1.`Id`,'') as lybid,
                                   s1.`No` as wpbh,
                                   s0.`Receiver` as jsrxm,
                                   '01'  as cklx,
                                   DATE_FORMAT(s0.`DeliveryTime`,'%Y%m%d%H%i%s') as cksj,
                                   (case when s0.`DeliveryDicType` = 8 then '1' else '2' end) as sjczlxdm,
                                   left(s3.`ComNo`,6) as sjly,
                                   DATE_FORMAT(s1.`CreateTime`,'%Y-%m-%d %H:%i:%s') as lrsj,
                                   s3.`ComNo` as lrdwdm,
                                   s3.`Name` as lrdwmc,
                                   s0.`Creator` as lrrxm,
                                   s4.`CardNo` as lrrsfzh,
                                   DATE_FORMAT(s0.`ModifyerTime`,'%Y-%m-%d %H:%i:%s') as xgsj,
                                   s3.`ComNo` as xgdwdm,
                                   s3.`Name` as xgdwmc,
                                   s4.`CardNo` as xgrsfzh,
                                   s0.`Creator` as xgrxm,
                                   CONCAT(s0.`Id`,'') as xxzjbh,
                                   '恒亦达信息科技(苏州)有限公司' as sjsbcj
                              FROM case_physical_evidence_transfere s0
                              join case_physical_evidence s1 on s0.`EvidenceId`=s1.`Id`
                              join cases s2 on s1.`CaseId`=s2.`Id` 
                              left join system_user s4 on s0.`CreatorId`=s4.`Id` 
                              left join system_organ s3 on s4.`OrgId`=s3.`Id`
                             where s0.`EvidenceStatus`=2
                               and `HistoryStatus`=0
                               and (s0.`ModifyerTime`>='{preTime.ToString("yyyy-MM-dd HH:mm:ss")}' OR s1.id in({string.Join(",", ids)}))  
                               and s1.`PushSucc` is not null ";
            var list = this._configRepository.GetDb().SqlQueryable<dynamic>(sql).ToList();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    var ret = Ajax<string>("/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSawpCkxx", new object[] { item }, token);
                    if (ret.Success)
                    {
                        Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSawpCkxx，\n2.6 涉案物品出库信息成功：【{Newtonsoft.Json.JsonConvert.SerializeObject(item)}】");
                    }
                    else
                    {
                        Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSawpCkxx，\n2.6 涉案物品出库信息失败：【{Newtonsoft.Json.JsonConvert.SerializeObject(new { ret, item })}】");
                    }
                }
            }
            else
            {
                Log.Information($"/datastandardapi/api/commonapi/saveOrUpdateBatch/TabSawpCkxx，\n2.6 涉案物品出库信息：数据库查询无数据");
            }
        }

        MainConfigEntity GetDataStandardConfig()
        {
            MainConfigEntity mainConfigEntity = _configRepository.Query(m => m.CategoryCode == EnumClass.DataStandardConfig && m.Class == EnumClass.DataStandardConfig).FirstOrDefault();
            if (mainConfigEntity == null)
            {
                mainConfigEntity = new MainConfigEntity();
                mainConfigEntity.Class = EnumClass.DataStandardConfig;
                mainConfigEntity.ClassName = "第三方系统数据同步配置";
                mainConfigEntity.CategoryCode = EnumClass.DataStandardConfig;
                mainConfigEntity.CategoryName = "第三方系统数据同步配置";
                mainConfigEntity.Content = Newtonsoft.Json.JsonConvert.SerializeObject(new { preTime = DateTime.Now.AddYears(-1) }, new Newtonsoft.Json.Converters.IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
                mainConfigEntity.Modifyer = mainConfigEntity.Creator = "sys";
                mainConfigEntity.ModifyerId = mainConfigEntity.CreatorId = 0;
                mainConfigEntity.ModifyerTime = mainConfigEntity.CreateTime = DateTime.Now;
                mainConfigEntity.OrganId = 0;
                mainConfigEntity.Status = true;
                mainConfigEntity.Id = _configRepository.Insert(mainConfigEntity);
            }
            return mainConfigEntity;
        }
        /// <summary>
        /// 获取token
        /// </summary>
        string GetToken()
        {
            const string appid = "APPID20241015092039"; //APPID20241015092039
            var ret = Ajax<string>($"/datastandardapi/api/commonapi/getToken?appId={appid}", null, null);
            if (ret.Success)
            {
                Log.Information($"/datastandardapi/api/commonapi/getToken?appId={appid}，\ntoken请求成功：【{ret.content}】");
                return ret.content;
            }
            else
            {
                Log.Information($"/datastandardapi/api/commonapi/getToken?appId={appid}，\ntoken请求失败：【{ret.statusMessage}】");
                return "";
            }
        }
        /// <summary>
        /// 发送请求
        /// </summary>
        ResultEntity<T> Ajax<T>(string url, object data, string token)
        {
            ResultEntity<T> ret = new ResultEntity<T>() { statusMessage = "请求失败", statusCode = "ERROR" };
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
            if (!string.IsNullOrEmpty(token))
            {
                client.DefaultRequestHeaders.Add("token", token);
            }
            var httpContent = new System.Net.Http.StringContent("");
            if (data != null)
                httpContent = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
            try
            {
                string _api = "http://92.187.7.248:12010";
                Task<HttpResponseMessage> task = null;
                if (url.Contains("getToken"))
                {
                    task = client.GetAsync(_api + url);
                }
                else
                {
                    task = client.PostAsync(_api + url, httpContent);
                    Log.Information($"请求地址：{_api + url}");
                }
                task.Wait();
                var resp = task.Result;
                if (resp.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var strTask = resp.Content.ReadAsStringAsync();
                    strTask.Wait();
                    ret = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultEntity<T>>(strTask.Result);
                    return ret;
                }
                else
                {
                    switch (resp.StatusCode)
                    {
                        case System.Net.HttpStatusCode.NotFound:
                            ret.statusMessage = "接口未找到";
                            break;
                        case System.Net.HttpStatusCode.Forbidden:
                            ret.statusMessage = "接口禁止访问";
                            break;
                        case System.Net.HttpStatusCode.Unauthorized:
                            ret.statusMessage = "权限未认证";
                            break;
                        case System.Net.HttpStatusCode.Created:
                            ret.statusMessage = "新建数据";
                            break;
                        default:
                            ret.statusMessage = "远程服务器异常";
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                ret.statusMessage = ex.ToString();
                Log.Information("出现异常：" + ex.ToString());
            }
            return ret;
        }
        #endregion 执法办案管理中心信息系统
    }
}
